﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Xml;
using UnityEngine;

namespace Hydrogen.MarkovChain.SolidMap2DScene
{
    /// <summary>
    /// 读取并翻译规则
    /// </summary>
    [Serializable]
    public class Interpreter
    {
        private string _ruleXmlAddr;
        private SolidMap2dResManager _resMgr;
        private XmlDocument _ruleDoc;
        [UnityEngine.SerializeField]
        private RuleRoot _ruleRoot;

        public List<RuleSP> SP => this._sp;
        [UnityEngine.SerializeField]
        private List<RuleSP> _sp = new List<RuleSP>();

        public bool IsInited { get; private set; }

        public Interpreter(SolidMap2dResManager resMgr, string ruleXmlAddr)
        {
            this._resMgr = resMgr;
            this._ruleXmlAddr = ruleXmlAddr;
        }

        public void Init()
        {
            IsInited = false;
            var xml = this._resMgr.GetRuleText(this._ruleXmlAddr);
            this._ruleDoc = new XmlDocument();
            this._ruleDoc.LoadXml(xml);
            if (this._ruleDoc.ChildNodes.Count <= 0) return;

            RuleNodeBase temp;
            foreach (XmlNode item in this._ruleDoc.ChildNodes)
            {
                temp = RuleNodeBase.Create(item);

                if (temp == null) continue;

                if (this._ruleRoot == null && temp is RuleRoot)
                    this._ruleRoot = RuleNodeBase.Create(item) as RuleRoot;
            }
            if (this._ruleRoot == null) return;

            this._sp = this._ruleRoot.RuleSPs;

            IsInited = true;
        }

        public bool TryExcute(Func<IRuleNodeSolidReplace, bool> excuteActive)
        {
            if (!IsInited) return false;

            return this._ruleRoot.TryExcute(excuteActive);
        }

        public void Reset()
        {
            if (!IsInited) return;
            this._ruleRoot?.Reset();
        }


    }
}
